package com.elite.groovy.controller;

import cn.hutool.http.HtmlUtil;
import com.elite.groovy.service.ProcessServiceRequire;
import com.elite.groovy.util.EliteBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
@Controller
@ResponseBody
public class ScriptController {

    @Autowired
    private ProcessServiceRequire processServiceRequire;

    @Autowired
    private EliteBean eliteBean;

    /**
     * 调用类路径下的groovy脚本
     *
     * @param groovyName
     * @param request
     * @param response
     * @throws Exception
     */
//    @RequestMapping(value = "/GeneralService/{groovyName}")
//    @CrossOrigin
//    public void getOneQuestionService(@PathVariable String groovyName, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        StopWatch stopWatch = new StopWatch();
//        response.setContentType("application/json;charset=utf-8");
//        response.setCharacterEncoding("utf-8");
//        log.debug("====================================Execute Script [{}] Start======================================================", groovyName);
//        PrintWriter out = response.getWriter();
//        try {
//            stopWatch.start();
//            processServiceRequire.doOldGeneralService(groovyName, request, response);
//        } catch (FileNotFoundException e) {
//            groovyName = HtmlUtil.filter(groovyName);
//            out.print(groovyName + " Groovy Script Not Found");
//        } catch (Exception e) {
//            log.error("", e);
//            out.print(e.getMessage());
//        } finally {
//            stopWatch.stop();
//            log.debug("Execute Script: [{}] End. And Spend: [{}] ms", groovyName, stopWatch.getTotalTimeMillis());
//            log.debug("=====================================Execute Script [{}] End========================================================", groovyName);
//        }
//    }

    /**
     * 调用数据库中的groovy脚本
     *
     * @param groovyName
     * @param request
     * @param response
     * @throws IOException
     */
    @CrossOrigin
    @RequestMapping("/call/{groovyName}")
    public void invokeByName(@PathVariable String groovyName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        log.debug("====================================Execute DB Script [{}] Start======================================================", groovyName);
        PrintWriter out = response.getWriter();
        try {
            Map<String, Object> groovyMap = eliteBean.getGroovyScriptByDB(groovyName);
            if (groovyMap == null) {
                groovyName = HtmlUtil.filter(groovyName);
                out.print(groovyName + " Groovy Script Not Found");
                return;
            }
            String groovyContent = groovyMap.get("GROOVY_CONTENT").toString();
            Timestamp modifiedDate = (Timestamp) groovyMap.get("MODIFIED_TIME");
            long modifiedDateLong = modifiedDate.getTime();
            processServiceRequire.doDbGroovyScriptService(groovyName, groovyContent, modifiedDateLong, request, response);
        } catch (Exception e) {
            log.error("", e);
            out.print(e.getMessage());
        } finally {
            stopWatch.stop();
            log.debug("Execute DB Script: [{}] End. And Spend: [{}] ms", groovyName, stopWatch.getTotalTimeMillis());
            log.debug("=====================================Execute DB Script [{}] End========================================================", groovyName);

        }
    }

    /**
     * 调用数据库中的groovy脚本
     *
     * @param groovyName
     * @param request
     * @param response
     * @throws IOException
     */
    @CrossOrigin
    @RequestMapping("/api/{groovyName}")
    public void apiByName(@PathVariable String groovyName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        log.debug("====================================Execute DB Script [{}] Start======================================================", groovyName);
        PrintWriter out = response.getWriter();
        try {
            Map<String, Object> groovyMap = eliteBean.getGroovyScriptByDB(groovyName);
            if (groovyMap == null) {
                groovyName = HtmlUtil.filter(groovyName);
                out.print(groovyName + " Groovy Script Not Found");
                return;
            }
            String groovyContent = groovyMap.get("GROOVY_CONTENT").toString();
            Timestamp modifiedDate = (Timestamp) groovyMap.get("MODIFIED_TIME");
            long modifiedDateLong = modifiedDate.getTime();
            processServiceRequire.doDbGroovyScriptService(groovyName, groovyContent, modifiedDateLong, request, response);
        } catch (Exception e) {
            log.error("", e);
            out.print(e.getMessage());
        } finally {
            stopWatch.stop();
            log.debug("Execute DB Script: [{}] End. And Spend: [{}] ms", groovyName, stopWatch.getTotalTimeMillis());
            log.debug("=====================================Execute DB Script [{}] End========================================================", groovyName);

        }
    }





    /**
     * 调用数据库中的groovy脚本
     *
     * @param groovyName
     * @param request
     * @param response
     * @throws IOException
     */
    @CrossOrigin
    @RequestMapping("/GeneralService/{groovyName}")
    public void GeneralServiceByName(@PathVariable String groovyName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        log.debug("====================================Execute DB Script [{}] Start======================================================", groovyName);
        PrintWriter out = response.getWriter();
        try {
            Map<String, Object> groovyMap = eliteBean.getGroovyScriptByDB(groovyName);
            if (groovyMap == null) {
                groovyName = HtmlUtil.filter(groovyName);
                out.print(groovyName + " Groovy Script Not Found");
                return;
            }
            String groovyContent = groovyMap.get("GROOVY_CONTENT").toString();
            Timestamp modifiedDate = (Timestamp) groovyMap.get("MODIFIED_TIME");
            long modifiedDateLong = modifiedDate.getTime();
            processServiceRequire.doDbGroovyScriptService(groovyName, groovyContent, modifiedDateLong, request, response);
        } catch (Exception e) {
            log.error("", e);
            out.print(e.getMessage());
        } finally {
            stopWatch.stop();
            log.debug("Execute DB Script: [{}] End. And Spend: [{}] ms", groovyName, stopWatch.getTotalTimeMillis());
            log.debug("=====================================Execute DB Script [{}] End========================================================", groovyName);

        }
    }


}
